﻿using Autofac;
using Dapper.Sharding;
using FastApi.Attributes;
using System.Text;
using System.Text.Json.Nodes;
using Test.Dto;

namespace Test
{
    /// <summary>
    /// 主页
    /// </summary>
    /// <remarks>
    /// 这是主页的备注信息呢
    /// </remarks>
    /// <swag-group>分组一</swag-group>
    public class HomeModule
    {
        readonly DistributedTransaction tran;
        ILifetimeScope scope0;

        public HomeModule(DistributedTransaction tran, ILifetimeScope scope0)
        {
            this.tran = tran;
            this.scope0 = scope0;
        }

        [FastPost(true)]
        public MySqlEntity A(MySqlEntity entity, string json, JsonObject obj)
        {
            return null;
        }

        [FastPost]
        public List<MySqlEntity> A2(MySqlEntity entity)
        {
            return null;
        }

        [FastPost]
        public MySqlEntity[] A3(MySqlEntity entity)
        {
            return null;
        }

        [FastPost]
        public Task<List<MySqlEntity>> A4(MySqlEntity entity)
        {
            return null;
        }

        [FastPost]
        public Task<List<MySqlEntity>> A5(MySqlEntity[] entity)
        {
            return null;
        }

        [FastPost]
        public Task<List<MySqlEntity>> A6(List<MySqlEntity> entity)
        {
            return null;
        }

        [FastPost]
        public Task<BaseEntity<List<MySqlEntity>>> A7(BaseEntity<MySqlEntity> entity)
        {
            return null;
        }

        /// <summary>
        /// 添加接口
        /// </summary>
        /// <param name="a">名字</param>
        /// <returns></returns>
        /// <remarks>
        /// 这是对接口的描述111
        /// 换行的描述2222
        /// </remarks>
        /// <swag-res>{code:0,data:{},msg:""}</swag-res>
        public static string Add(string a)
        {
            return "你好" + a;
        }

        /// <summary>
        /// 自定义body
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        /// <swag-body>{name:"里斯",sex:1}</swag-body>
        /// <swag-res>{code:0,data:{},msg:""}</swag-res>
        [FastFilterClear]
        public string Add2([FastBody] string a)
        {
            return "你好2" + a;
        }

        /// <summary>
        /// 表单上传
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        /// <swag-query>
        ///     id.string.true@这是个id
        ///     name.string.true@名字 
        ///     sex.string.false@性别 
        /// </swag-query>
        /// <swag-form>
        ///     addrss.string.true@地址
        ///     phone.string@手机 
        ///     fileName.file.true@文件
        /// </swag-form>
        [FastPost]
        public async Task<string> UploadFiles([FastQuery] int id, [FastQuery] string name, [FastQuery] string sex, [FastQuery] int age, [FastForm] string address, [FastForm] string addrss, [FastForm] string phone, IFastHttp _http)
        {
            var fileName = _http.GetFileName(0);
            throw new Exception("发生异常，删除失败了");
            return "删除" + id;
        }

        public async Task<string> TestAsync()
        {
            await Task.Delay(100);
            return "测试异步";
        }

        public async ValueTask<string> VAsync()
        {
            return "测试valueTask";
        }

        [FastCustomer]
        public async Task MyAsync(HttpContext context)
        {
            await context.Response.WriteAsJsonAsync(new { data = "这是自定义输出" });
        }

        public void db()
        {
            DbHelper.peopleTable.Insert(new People { Name = "里斯" + DateTime.Now }, tran);
            DbHelper.Database.Query("select * form ababa");
        }

        public async Task db2()
        {
            await DbHelper.peopleTable.InsertAsync(new People { Name = "里斯" + DateTime.Now }, tran);
        }

        public void db3(DistributedTransaction tran2)
        {
            DbHelper.peopleTable.Insert(new People { Name = "里斯" + DateTime.Now }, tran2);
        }

        public long dbQuery(List<int> aa)
        {
            return DbHelper.peopleTable.Count();
        }

        public string Autofac(int id, string name, ILifetimeScope scope)
        {
            Console.WriteLine(id + name);
            var db = scope.Resolve<IMyDatabase>();
            var db2 = scope0.ResolveNamed<IMyDatabase>("pg");
            return db.Get() + db2.Get();
        }

        public string Http(IFastHttp http)
        {
            var token = http.GetReqHeader("token");
            http.SetResHeader("token", "servertoken");
            Console.WriteLine($"token==>{token}");

            var sessionid = http.GetCookie("sessionid");
            http.SetCookie("sessionid", "serversessionid");
            //http.SetCookie("sessionid", "serversessionid", DateTimeOffset.Now.AddDays(100));
            Console.WriteLine($"sessionid==>{sessionid}");
            return "IHttp模块";
        }

        [FastPost]
        public void AddP([FastForm] People p)
        {
            DbHelper.peopleTable.Insert(p);
        }

        public People All()
        {
            return DbHelper.peopleTable.GetById(1);
        }

        public PageEntity<People> page()
        {
            return DbHelper.peopleTable.GetByPageAndCount(1, 1);
        }

        public async Task Down(IFastHttp _http)
        {
            StringBuilder sb = new();
            for (int i = 0; i < 100000; i++)
            {
                sb.Append(i + " ");
            }
            using var ms = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));
            await _http.WriteFileAsync(ms, "1.txt");
            await _http.DisposeAsync();
        }

        public async IAsyncEnumerable<int> TestIAsync1()
        {
            int[] arr = [1, 2, 3, 4];
            foreach (var item in arr)
            {
                await Task.Delay(1);
                yield return item;
            }
        }

        public async IAsyncEnumerable<People> TestIAsync2()
        {
            int[] arr = [1, 2, 3, 4];
            foreach (var item in arr)
            {
                await Task.Delay(1);
                yield return new People { Id = item, Name = "里斯" + item };
            }
        }

        public static async IAsyncEnumerable<People> TestIAsyncDb()
        {
            var list = DbHelper.Database.QueryUnbufferedAsync<People>("select * from people limit 10");
            await foreach (var item in list)
            {
                yield return item;
            }
        }

        public static IAsyncEnumerable<People> TestIAsyncDb2()
        {
            return DbHelper.Database.QueryUnbufferedAsync<People>("select * from people limit 2");

        }

        public static string TestGet(int id, string name, double dv, decimal dc, DateTime now, bool ok)
        {
            return id + name + dv + dc + now.ToString() + ok;
        }

        /// <swag-form>
        ///     f1.file.true@文件
        /// </swag-form>
        [FastUpload]
        public void ZZZ([FastForm] People p, [FastForm] People p2, [FastQuery] People p3, [FastQuery] People p4)
        {
            DbHelper.peopleTable.Insert(p);
        }

        [FastFilterClear]
        [FastPath("code")]
        public string TestPath(IFastHttp http)
        {
            return http.RouteData;
        }
    }
}
